#coding=utf-8

'''
@author: tongji
@contact: tongji@rekoo.com
'''

import time
import sys
import datetime
from django.contrib.auth.models import User
from copy import deepcopy

from basecallback import basecallback
from statistic_config import whitelist

class TimeviewMiddleware(object):
    def process_request(self, request):
        self.start_time = time.time()
    
    def process_response(self, request, response):
        end_time = time.time()
        path_name = request.path.strip("/").replace('/', '.')
        if not hasattr(self, 'start_time'):
            return response

        exec_time = end_time - self.start_time
        if exec_time !=0:
            method = request.REQUEST.get('method')
            if method is None:
                print '%s timeit view: %s: %.3f' % (str(datetime.datetime.now()),path_name, exec_time)
            else:
                print '%s timeit view: %s.%s: %.3f' % (str(datetime.datetime.now()),path_name, method, exec_time)
        return response
    

from logger import Logger

class StatisticsMiddleware(object):
    '''统计中间件'''
    def __init__(self):
        self.resetargs()
        self.resetdata()
        self.output = sys.stdout.write
        self.formatter = ['ts', 'uid', 'scene', 'level', 'stay', 'action', 'v1', 'v2', 'v3', 'v4', 'num']
    
    def process_request(self, request):
        return None
    
    def process_view(self, request, view_func, view_args, view_kwargs):
        self.resetdata() # 在执行视图函数之前先重置数据
        key = view_func.__module__ + '.' + view_func.__name__ # 全局名字
        
        if key in whitelist: #　如果在设置的白名单中，获取前后值，记录对应数据；否则不记录
            self.get_args(request, scene='before') # 获取视图执行之前的状态
            returndata = view_func(request, *view_args, **view_kwargs) # 执行视图函数
            self.get_args(request, scene='after') # 获取视图之后的状态
            
            callback = whitelist.get(key,None) # 获取回调函数
            if callback:
                try:
                    data = callback(request, self.args)
                except Exception, e:
                    data = {}
                    print e
                self.statdata = self.basecallback(request, key)
                self.statdata.update(data)
            if self.statdata['success']:
                self.write()
            else:
                pass
#            print self.args
            self.resetargs()
            return returndata
    
    def process_response(self, request, response):
        return response
    
    def get_args(self, request, scene=None):
        rk_user = request.user
        self.args[scene]['first_name'] = rk_user.first_name
#        args[scene]['kb'] = rk_user.gameinfo.kb
#        args[scene]['level'] = rk_user.gameinfo.level
#        args[scene]['exp'] = rk_user.gameinfo.exp
    
    def basecallback(self, request, key):
        rk_user = request.user
        data = {'uid':rk_user.id, 'action':key, 'ts':time.strftime('%H:%M:%S'), 'scene':None, 'level':None, 'success':True}
        return data
    
    def format(self, data):
        '''格式化数据'''
        delimiter = '\t'
        record = []
        for item in self.formatter:
            record.append(data.get(item, None))
        return delimiter.join(map(str, record))

    def write(self):
        '''将数据写到规定的渠道'''
        try:
            record = self.format(self.statdata)
        except Exception,e:
            print e
        else:
            self.output(record + '\n')
            
    def setoutput(self, output_handler = None):
        '''设置输出方式'''
        if output_handler:
            self.output = output_handler
        else:
            self.output = sys.stdout.write

    def resetdata(self):
        '''重置数据为空'''
        self.statdata = {}
    
    def resetargs(self):
        self.args = {'before':{}, 'after':{}}